package com.alinesno.cloud.common.web.base.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alinesno.cloud.base.boot.entity.ManagerAccountEntity;
import com.alinesno.cloud.common.facade.orm.entity.BaseEntity;
import com.alinesno.cloud.common.facade.orm.repository.IBaseJpaRepository;
import com.alinesno.cloud.common.facade.pageable.DatatablesPageBean;
import com.alinesno.cloud.common.facade.response.ResponseBean;
import com.alinesno.cloud.common.facade.response.ResponseGenerator;
import com.alinesno.cloud.common.web.base.utils.WebUploadUtils;
import com.alinesno.cloud.common.web.login.session.CurrentAccountSession;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.lang.UUID;

/**
 * 工程基类
 * 
 * @author WeiXiaoJin
 * @since 2018年11月20日 上午8:10:06
 */
public class BaseController {

	private static final Logger log = LoggerFactory.getLogger(BaseController.class);

	public final static String DASHBAORD_PATH = "/dashboard"; // 主面板入口

	/**
	 * 本地保存路径 
	 */
	@Value("${alinesno.file.local.path:/tmp/}")
	protected String localPath ; 
	
	@Value("${spring.application.name:consumer}")
	private String applicationName ; 

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpServletResponse response;

	@Autowired
	protected HttpSession session;

	@Value("${alinesno.storage.cloud.path:-1}")
	private String uploadCloudPath ; 
	
	protected static final int SUCCESS = 200 ; 
	protected static final int FAIL = 400 ; 

	/**
	 * Spring mvc 重定向
	 * 
	 * @param url
	 * @return
	 */
	public String redirect(String url) {
		return "redirect:" + url;
	}

	/**
	 * 返回成功
	 * 
	 * @return
	 */
	protected ResponseBean ok() {
		return ok(null);
	}

	/**
	 * 返回成功
	 * 
	 * @return
	 */
	protected ResponseBean ok(String message) {
		return ResponseGenerator.ok(message);
	}

	/**
	 * 返回失败
	 * 
	 * @return
	 */
	protected ResponseBean fail() {
		return fail(null);
	}

	/**
	 * 返回失败
	 * 
	 * @return
	 */
	protected ResponseBean fail(String message) {
		return ResponseGenerator.fail(message);
	}

	public <T extends BaseEntity> DatatablesPageBean toPage(Model model, Specification<T> specification, IBaseJpaRepository<T, String> jpa, DatatablesPageBean page, Sort sort) {
		DatatablesPageBean p = new DatatablesPageBean();
		return p;
	}

	public <T extends BaseEntity> DatatablesPageBean toPage(Model model, Specification<T> specification,
			IBaseJpaRepository<T, String> jpa, DatatablesPageBean page) {
		Sort sort = Sort.by(Direction.DESC, "addTime");
		return toPage(model, specification, jpa, page, sort);
	}

	/**
	 * @Description 响应Ajax请求
	 * @param response
	 * @param content
	 *            响应内容
	 * @param charset
	 *            字符编码
	 * @throws IOException
	 */
	public void outPrint(HttpServletResponse response, String content, String charset) throws IOException {
		response.setContentType("text/html;charset=" + charset);
		PrintWriter out = response.getWriter();
		out.print(content);
		out.flush();
	}
	
	public void outPrint(HttpServletResponse response, String content) throws IOException {
		this.outPrint(response, content, "UTF-8");
	}
	
	/**
	 * 多个文件上传
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws IORuntimeException 
	 */
	public List<Map<String, Object>> multiUploadFile(HttpServletRequest request , boolean isCloud) throws IORuntimeException, IOException {
	
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>() ;
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		
		String userId = null ; 
		String userName = null ; 

		if(isCloud) {
			Assert.hasLength(uploadCloudPath , "云存储路径不能为空.");
			ManagerAccountEntity account = CurrentAccountSession.get(request) ; 
			if(account != null) {
				userId = account.getId() ; 
				userName = account.getName() ; 
			}
		}

		for (int i = 0; i < files.size(); i ++ ) {
			MultipartFile file = files.get(i);
			Map<String, Object> m = new HashMap<String, Object>() ; 
			
			String fileType = FileTypeUtil.getType(file.getInputStream()) ; 
			String saveFileName = UUID.fastUUID().toString() + "." + fileType ; 
			String format = DateUtil.format(new Date(), "yyyy/MM/dd");
			String path = localPath + File.separator + format  ; 
	
			FileUtil.mkdir(path) ; 
			File dest = new File(path + File.separator + saveFileName);
			try {
				String filepath =  format + File.separator + saveFileName ; 
				file.transferTo(dest); // 保存本地
				
				if(isCloud) {
					filepath = WebUploadUtils.transferFile(uploadCloudPath, dest , fileType , userId , userName , applicationName) ;
					log.debug("云存储上传路径:{}" , filepath);
				}
				
				log.info("第" + (i + 1) + "个文件上传成功");
				
				m.put("filename", file.getOriginalFilename()) ; 
				m.put("saveFilename", saveFileName) ; 
				m.put("filepath", filepath) ;
				
				list.add(m) ; 
			} catch (Exception e) {
				log.error(e.toString(), e);
			}
		}
		return list;
	}

}
